package io.gitee.mingbaobaba.security.plugin.redis.repository;

import io.gitee.mingbaobaba.security.core.repository.SecurityCaptchaRepository;
import io.gitee.mingbaobaba.security.plugin.redis.constants.SecurityRedisConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.text.MessageFormat;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>验证码redis实现</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/21 10:42
 */
public class SecurityCaptchaRedisRepository implements SecurityCaptchaRepository {

    private final StringRedisTemplate stringRedisTemplate;

    public SecurityCaptchaRedisRepository(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public String saveCaptcha(String code, long expiry) {
        String uuid = UUID.randomUUID().toString();
        String redisKey = MessageFormat.format(SecurityRedisConstant.CAPTCHA_KEY, uuid, code).toLowerCase();
        stringRedisTemplate.opsForValue().set(redisKey, code, expiry, TimeUnit.SECONDS);
        return uuid;
    }

    @Override
    public Boolean validCaptcha(String key, String code) {
        String validCodeKey = MessageFormat.format(SecurityRedisConstant.CAPTCHA_KEY, key, code).toLowerCase();
        if (StringUtils.isBlank(validCodeKey)) {
            return false;
        }
        boolean flag = Boolean.TRUE.equals(stringRedisTemplate.hasKey(validCodeKey));
        stringRedisTemplate.delete(validCodeKey);
        return flag;
    }
}
